// import storage from 'store'
// import session from '@/utils/session'
import { getTags, getCategories } from '@/api/blog'

const blog = {
  state: {
    categories: [],
    categoriesLoaded: false,
    tags: [],
    tagsLoaded: false
  },
  getters: {
    tagName: (state) => (id) => {
      return state.tags.find(tag => tag.id === id).name
    },
    categoryName: (state) => (id) => {
      return state.categories.find(c => c.id === id)
    }
  },
  mutations: {
    setTags: (state, tags) => {
      state.tags = tags
      state.tagsLoaded = true
    },
    setCategories: (state, categories) => {
      state.categories = categories
      state.categoriesLoaded = true
    }
  },
  actions: {
    initTags ({ commit, state }) {
      if (state.tagsLoaded) {
        return new Promise((resolve) => {
          resolve(true)
        })
      }
      return getTags().then(res => {
        commit('setTags', res.result)
        return true
      })
    },
    initCategories ({ commit, state }) {
      if (state.categoriesLoaded) {
        return new Promise((resolve) => {
          resolve(true)
        })
      }
      return getCategories().then(res => {
        commit('setCategories', res.result)
        return true
      })
    }
  }
}

export default blog
